/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.front.order;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.plugins.wxmsg.WxMsgUtil;
import shop.services.front.order.OrderService;
import shop.services.front.order.bean.Order;
import shop.services.front.orderdetail.OrderdetailService;
import shop.services.front.orderdetail.bean.Orderdetail;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名称：OrderController
 * @创建人：Wzl
 * @创建时间：2017-09-20 下午15:48:44
 * @版本号：1.0
 * @描述：订单
 */
@Controller
@RequestMapping("/front/order/")
public class OrderController extends FrontBaseController<Order> {
    private final static String ORDER_PAY_TYPE_OFFLINE = "offline";
    private final static String ORDER_CHECK_STATUS_INIT = "init";
    @Resource
    private OrderService orderService;
    @Resource
    private OrderdetailService orderdetailService;
    @Resource
    private UserService userService;

    @Override
    public Services<Order> getService() {
        return orderService;
    }


    /**
     * 跳转到订单列表页面
     *
     * @return
     */
    @RequestMapping("toOrderList")
    public String toOrderList() {
        return "/front/order/allOrder";
    }

    /**
     * 跳转到订单详情页面（个人中心入口）
     *
     * @return
     */
    @RequestMapping("toOrderDetail")
    public String toOrderDetail() {
        return "/front/order/orderDetail";
    }

    /**
     * 跳转到订单详情页面（购物车入口）
     *
     * @return
     */
    @RequestMapping("toCartOrderDetail")
    public String toCartOrderDetail() {
        return "/front/order/cartOrderDetail";
    }

    /**
     * 跳转到订单详情页面（商品详情入口）
     *
     * @return
     */
    @RequestMapping("toProductOrderDetail")
    public String toProductOrderDetail() {
        return "/front/order/productOrderDetail";
    }

    /**
     * 跳转到分销商首页
     *
     * @return
     */
    @RequestMapping("toSellerList")
    public String toSellerList() {
        return "/front/order/sellerList";
    }

    /**
     * 跳转到购买会员页面
     *
     * @return
     */
    @RequestMapping("toSellerPay")
    public String toSellerPay() {
        return "/front/order/sellerPay";
    }

    /**
     * 跳转到线下转账申请页面
     *
     * @return
     */
    @RequestMapping("toOfflinePay")
    public String toOfflinePay() {
        return "/front/order/lineSellerPay";
    }


    /**
     * 查询订单列表
     * @param order
     * @return orderList
     */
    @RequestMapping(value = "selectOrderList", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderList(HttpServletRequest request, Order order) {
        JSONResult jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute("userInfo");
        order.setUserID(user.getId());
        List<Order> orderList = orderService.selectList(order);//查询用户订单列表
        for (int i = 0; i < orderList.size(); i++) {//遍历订单列表
            Order rs = orderList.get(i);
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderID(rs.getId());//赋值
            orderList.get(i).setOrderdetails(orderdetailService.selectOrderDetailList(orderdetail));//查询订单详情列表
        }
        jsonResult.setData(orderList);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 查询订单详情（个人中心入口）
     * @return
     */
    @RequestMapping(value = "selectOrderDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderDetail(Orderdetail orderdetail) {
        Orderdetail rs = new Orderdetail();
        rs.setOrderID(orderdetail.getOrderID());
        List<Orderdetail> rsList = orderdetailService.selectOrderDetailList(rs);
        return new JSONResult(rsList, true);
    }

    /**
     * 查询用户订单地址
     * @param order
     * @return
     */
    @RequestMapping(value = "selectOrderAddress", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrderAddress(Order order) {
        order = orderService.selectOne(order);
        jsonResult = new JSONResult();
        jsonResult.setData(order);
        return jsonResult;
    }

    /**
     * 查询分销订单
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectStoreOrder")
    @ResponseBody
    public JSONResult selectStoreOrder(HttpSession session, Order order) throws Exception {
        JSONResult jsonResult = new JSONResult();
        User user = (User) session.getAttribute("userInfo");
        order.setUserID(user.getId());
        List<Order> orderList = orderService.selectStoreOrder(order);//查询分销订单列表
        for (int i = 0; i < orderList.size(); i++) {//遍历分销订单列表
            Order rs = orderList.get(i);
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderID(rs.getId());//赋值
            orderList.get(i).setOrderdetails(orderdetailService.selectOrderDetailList(orderdetail));//查询订单详情列表
        }
        jsonResult.setData(orderList);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 线下转账申请
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "offlinePay", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult offlinePay(HttpSession session, Order order) throws Exception {
        jsonResult = new JSONResult();
        User user = (User) session.getAttribute("userInfo");
        Order orderInfo = new Order();
        orderInfo.setUserID(user.getId());
        orderInfo.setCheckStatus(ORDER_CHECK_STATUS_INIT);
        orderInfo = orderService.selectOne(orderInfo);
        if (orderInfo != null) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("您的线下支付申请正在审核，请耐心等待！");
            return jsonResult;
        } else {
            order.setPayType(ORDER_PAY_TYPE_OFFLINE);
            order.setCheckStatus(ORDER_CHECK_STATUS_INIT);
            order.setUserID(user.getId());
            orderService.insert(order);
            return jsonResult;
        }
    }

    /**
     * 判断用户审核状态
     * @param order
     * @return
     */
    @RequestMapping(value = "selectCheckStatus", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectCheckStatus(HttpSession session, Order order) {
        String checkStatus = null;
        User user = (User) session.getAttribute("userInfo");
        order.setUserID(user.getId());
        order = orderService.selectOne(order);
        jsonResult = new JSONResult();
        if (order != null)
            checkStatus = order.getCheckStatus();
        jsonResult.setData(checkStatus);
        return jsonResult;
    }

    /**
     * 分销商发货
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateSendOrderJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateSendOrderJson(Order order) throws Exception {
        jsonResult = new JSONResult();
        orderService.update(order);
        //订单发货消息通知
        order = orderService.selectOne(order);
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setOrderID(order.getId());
        List<Orderdetail> orderdetailList = orderdetailService.selectList(orderdetail);
        orderdetail.setId(orderdetailList.get(0).getId());
        orderdetail = orderdetailService.selectOne(orderdetail);
        User user = new User();
        user.setId(order.getUserID());
        user = userService.selectOne(user);
        Map<String, String> msgParam = new HashMap<>();
        msgParam.put("first", "亲爱的" + user.getNickname() + "，您的订单已经发货了，请耐心等待哦~");
        msgParam.put("keyword1", orderdetail.getProductName());
        msgParam.put("keyword2", order.getExpressCompany());
        msgParam.put("keyword3", order.getExpressNum());
        msgParam.put("keyword4", order.getAddressArea() + order.getAddressDetail());
        msgParam.put("keyword5", "--");
        msgParam.put("remark", "点击查看订单详情");
        if ("y".equals(user.getOrderSendStatus()))
            WxMsgUtil.sendProductMsg(msgParam, systemManager.getAccessToken(), user.getOpenID());
        return jsonResult;
    }

    /**
     * 分销商确认收货
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateFinishOrderJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateFinishOrderJson(Order order) throws Exception {
        jsonResult = new JSONResult();
        orderService.update(order);
        //订单发货消息通知
        order = orderService.selectOne(order);
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setOrderID(order.getId());
        List<Orderdetail> orderdetailList = orderdetailService.selectList(orderdetail);
        orderdetail.setId(orderdetailList.get(0).getId());
        orderdetail = orderdetailService.selectOne(orderdetail);
        User user = new User();
        user.setId(order.getUserID());
        user = userService.selectOne(user);
        Map<String, String> msgParam = new HashMap<>();
        msgParam.put("first", "亲爱的" + user.getNickname() + "，您有一个订单状态变更为已完成");
        msgParam.put("keyword1", order.getId());
        msgParam.put("keyword2", order.getCreateTime());
        msgParam.put("remark", "点击查看订单详情");
        if ("y".equals(user.getOrderFinishStatus()))
            WxMsgUtil.sendSubOrderFinishMsg(msgParam, systemManager.getAccessToken(), user.getOpenID());
        if (!StringUtils.isBlank(user.getPid())) {
            User supUser = new User();
            supUser.setId(user.getPid());
            supUser = userService.selectOne(supUser);
            Map<String, String> msgParam2 = new HashMap<>();
            msgParam2.put("first", "亲爱的" + supUser.getNickname() + "，您有一个分销订单状态变更为已完成");
            msgParam2.put("keyword1", order.getId());
            msgParam2.put("keyword2", orderdetail.getProductName());
            msgParam2.put("keyword3", order.getCreateTime());
            msgParam.put("remark", "点击查看订单详情");
            if ("y".equals(supUser.getOrderSubFinishStatus()))
                WxMsgUtil.sendOrderFinishMsg(msgParam, systemManager.getAccessToken(), supUser.getOpenID());
        }
        return jsonResult;
    }

    /**
     * 下级用户确认收货
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateSubFinishOrderJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateSubFinishOrderJson(Order order) throws Exception {
        jsonResult = new JSONResult();
        orderService.update(order);
        //订单发货消息通知
        order = orderService.selectOne(order);
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setOrderID(order.getId());
        List<Orderdetail> orderdetailList = orderdetailService.selectList(orderdetail);
        orderdetail.setId(orderdetailList.get(0).getId());
        orderdetail = orderdetailService.selectOne(orderdetail);
        User user = new User();
        user.setId(order.getUserID());
        user = userService.selectOne(user);
        Map<String, String> msgParam = new HashMap<>();
        msgParam.put("first", "亲爱的" + user.getNickname() + "，您有一个订单状态变更为已完成");
        msgParam.put("keyword1", order.getId());
        msgParam.put("keyword2", order.getCreateTime());
        msgParam.put("remark", "点击查看订单详情");
        if ("y".equals(user.getOrderSubFinishStatus()))
            WxMsgUtil.sendSubOrderFinishMsg(msgParam, systemManager.getAccessToken(), user.getOpenID());
        if (!StringUtils.isBlank(user.getPid())) {
            User supUser = new User();
            supUser.setId(user.getPid());
            supUser = userService.selectOne(supUser);
            Map<String, String> msgParam2 = new HashMap<>();
            msgParam2.put("first", "亲爱的" + user.getNickname() + "，您有一个分销订单状态变更为已完成");
            msgParam2.put("keyword1", order.getId());
            msgParam2.put("keyword2", orderdetail.getProductName());
            msgParam2.put("keyword3", order.getCreateTime());
            msgParam.put("remark", "点击查看订单详情");
            if ("y".equals(supUser.getOrderFinishStatus()))
                WxMsgUtil.sendOrderFinishMsg(msgParam, systemManager.getAccessToken(), supUser.getOpenID());
        }
        return jsonResult;
    }


    /**
     * 用户取消订单付款消息通知
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "sendPayFailedMsg", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult sendPayFailedMsg(Order order) throws Exception {
        logger.debug("order.getID"+order.getId());
        jsonResult = new JSONResult();
        orderService.update(order);
        //订单付款失败消息通知
        order = orderService.selectOne(order);
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setOrderID(order.getId());
        List<Orderdetail> orderdetailList = orderdetailService.selectList(orderdetail);
        orderdetail.setId(orderdetailList.get(0).getId());
        orderdetail = orderdetailService.selectOne(orderdetail);
        logger.debug("orderdetail.getID"+order.getId());
        User user = new User();
        user.setId(order.getUserID());
        user = userService.selectOne(user);
        logger.debug("user.getID"+order.getId());
        Map<String, String> msgParam = new HashMap<>();
        msgParam.put("first", "亲爱的" + user.getNickname() + "，请尽快处理未付款的订单，超时会自动关闭哟~");
        msgParam.put("keyword1", order.getCreateTime());
        msgParam.put("keyword2", order.getPtotal().toString());
        msgParam.put("keyword3", orderdetail.getProductName());
        msgParam.put("remark", "感谢您对纤纤蓓颖商城的支持！点击【详情】支付~");
        if ("y".equals(user.getOrderUnPayStatus()))
            WxMsgUtil.sendPayFailedMsg(msgParam, systemManager.getAccessToken(), user.getOpenID());
        return jsonResult;
    }
}
